package com.lz.netty.consumer2.project.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lz.netty.consumer2.common.entity.RequestVo;
import com.lz.netty.consumer2.common.entity.ResponseVo;
import com.lz.netty.consumer2.common.utils.DateUtils;
import com.lz.netty.consumer2.project.api.service.ApiService;
import com.lz.netty.consumer2.project.netty.ChannelStore;
import com.lz.netty.consumer2.project.netty.util.MsgUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;



/**
 * 虚拟现场 webflux测试
 *
 * @author xpp
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Resource
    ApiService apiService;

    @PostMapping("/nettyClient")
    public ResponseVo checkThread(@RequestBody RequestVo requestVo) {
        sendOneMsg(StrUtil.format("客户端,发送消息:{},日期:", JSONUtil.toJsonStr(requestVo), DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "\r\n"));
        return ResponseVo.success();
    }

    @GetMapping("/nettyC2")
    public ResponseVo nettyC2() {
        sendOneMsg(StrUtil.format("客户端,发送消息,日期:", DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "\r\n"));
        return ResponseVo.success();
    }

    public static void sendOneMsg(String msg) {
        for (Channel channel : ChannelStore.CHANNEL_GROUP) {
            ChannelFuture channelFuture =  channel.writeAndFlush(MsgUtil.buildMsg(channel.id().toString(), msg));
            //回调查看返回状态 ChannelFutureListener/channelFuture
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.cause() != null) {
                    logger.error("客户端2netty消息发送失败:", future.cause());
                } else if (future.isSuccess()) {
                    logger.info("客户端2netty消息发送成功:{}", msg);
                } else {
                    logger.error("客户端2Message send failed for an unknown reason.");
                }
            });
        }
    }

}
